package com.ews.onlineexchange.service.schedule;

import javax.annotation.Resource;
import javax.ejb.Schedule;
import javax.ejb.ScheduleExpression;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;

import org.hibernate.CacheMode;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;

import com.ews.onlineexchange.model.Bulletin;
import com.ews.onlineexchange.model.Trade;
/**
 * @author taylover
 *	中介机构统计（中选次数的等）
 */
@Named
@Singleton
@Startup
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class BulletinWinnerUpdateTimer {

	@Resource
	TimerService timerService;
	
	@Inject
	EntityManager entityManager;
	private static final String QUERY_ALL_BULLETIN_EQL = ""
			+ "	SELECT			b						"
			+ "	FROM			Bulletin b 				"
			+ "	WHERE 			b.tradeStatus = 'Agreed'			";
//	@Timeout
	@Schedule(hour="23", minute="0", second="0", info = "bulletinWinnerUpdate", persistent = false)
	public void check() {
		Session session = entityManager.unwrap( Session.class );
		long count = 0L;
		ScrollableResults sr = session.createQuery(QUERY_ALL_BULLETIN_EQL).setCacheMode( CacheMode.IGNORE ).scroll( ScrollMode.FORWARD_ONLY );
//
		while (sr.next()) {
			Bulletin bulletin = (Bulletin) sr.get(0);
			Trade successTrade = bulletin.getSuccessTrade();
			if(successTrade != null) bulletin.setWinnerId(successTrade.getSupplier().getId()); 
			session.update(bulletin);
			count++;
			if (count % 200 == 0) {
				session.flush();
			}
		}
		session.flush();
	}
	
	
}
